package tw.com.hitevision.whiteboard.android.widgets.floatView.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import tw.com.hitevision.whiteboard.android.widgets.floatView.enums.ShowPattern
import tw.com.hitevision.whiteboard.android.widgets.floatView.widget.appfloat.FloatManager

internal object LifecycleUtils {

    private var activityCount = 0
    private lateinit var application: Application

    fun setLifecycleCallbacks(application: Application) {
        LifecycleUtils.application = application
        application.registerActivityLifecycleCallbacks(object :
            Application.ActivityLifecycleCallbacks {

            override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {}

            override fun onActivityStarted(activity: Activity?) {
                if (activity != null) activityCount++
            }

            override fun onActivityResumed(activity: Activity?) = checkShow(activity)

            override fun onActivityPaused(activity: Activity?) {}

            override fun onActivityStopped(activity: Activity?) {
                if (activity != null) {
                    activityCount--
                    checkHide()
                }
            }

            override fun onActivityDestroyed(activity: Activity?) {}

            override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {}

        })
    }

    /**
     *  checkShow
     */
    private fun checkShow(activity: Activity?) {
        if (activity == null) return
        FloatManager.floatMap.forEach { (tag, manager) ->
            manager.config.apply {
                when {
                    showPattern == ShowPattern.BACKGROUND -> setVisible(false, tag)

                    needShow -> setVisible(activity.componentName.className !in filterSet, tag)
                }
            }
        }
    }

    /**
     *  checkHide
     */
    private fun checkHide() {
        if (isForeground()) return
        FloatManager.floatMap.forEach { (tag, manager) ->
            manager.config.apply {
                setVisible(showPattern != ShowPattern.FOREGROUND && needShow, tag)
            }
        }
    }

    fun isForeground() = activityCount > 0

    private fun setVisible(isShow: Boolean = isForeground(), tag: String?) =
        FloatManager.visible(isShow, tag)

}